package com.xjcs.saplingplan.adapter

import android.content.Context
import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
import com.xjcs.saplingplan.const.loadImage
import com.xjcs.saplingplan.databinding.ItemCountdownCateBinding
import com.xjcs.saplingplan.room.bean.countdown.PlanCateBean
import com.xjcs.saplingplan.utils.CountDownUtils

class CountdownCateAdapter(
    private val context: Context,
    private var data: MutableList<PlanCateBean> = mutableListOf(),
    val dragFinishCallback: (MutableList<PlanCateBean>) -> Unit,
    val onItemDelete: (Int, PlanCateBean) -> Unit
) : RecyclerView.Adapter<CountdownCateAdapter.ItemCountdownCateViewHolder>() {

    fun setData(newData: MutableList<PlanCateBean>) {
        this.data = newData
        notifyDataSetChanged()
    }

    // 提供外部获取当前数据（不可变副本）
    fun getData(): MutableList<PlanCateBean> {
        return data
    }

    // 用于外部调用的拖动排序方法
    fun onItemMove(fromPosition: Int, toPosition: Int) {
        if (fromPosition < data.size && toPosition < data.size) {
            // 交换数据源中的两个元素
            val fromItem = data.removeAt(fromPosition)
            data.add(toPosition, fromItem)
            // 通知 RecyclerView 该项已经移动（会有动画效果）
            notifyItemMoved(fromPosition, toPosition)
        }
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ItemCountdownCateViewHolder {
        val binding = ItemCountdownCateBinding.inflate(LayoutInflater.from(context), parent, false)
        return ItemCountdownCateViewHolder(binding)
    }

    override fun getItemCount(): Int = data.size

    override fun onBindViewHolder(holder: ItemCountdownCateViewHolder, position: Int) {
        val item = data.getOrNull(position)
        holder.bind(item)
    }

    class ItemCountdownCateViewHolder(
        private val binding: ItemCountdownCateBinding,
    ) : RecyclerView.ViewHolder(binding.root) {
        fun bind(item: PlanCateBean?) {
            item?.let {
                binding.ivImg.setBgColor(it.getCateBgColor())
                binding.ivImg.loadImage(CountDownUtils.getCateImg(it.planCateIcon))
                binding.tvCateName.text = it.planCateName
            }
        }
    }
}